Installation

  1. Install R
  2. Install RTools if you are on Windows
  3. Install RStudio

For more details, see Software and Package Versions.

Running This Code

  1. Ensure the installation steps above are completed
  2. Download a zip of the code and data here and unzip it
  3. In RStudio, open the src/src.Rproj file
  4. Then, open the src/index.Rmd file
  5. In RStudio:
    • Run all code: Click the Run drop down (top right of the code pane) and click Run All
    • Generate HTML version: Click knit (top left of code pane) and a file will be generated in docs/index.html

Libraries

Install R packages if needed.

# Required packages
required_packages <- c(
    "rmarkdown",
    "bookdown",
    "knitr",
    "tidyverse",
    "purrr",
    "glue",
    "lubridate",
    "scales",
    "patchwork",
    "DiagrammeR",
    "DiagrammeRsvg",
    "webshot2",
    "magick",
    "rsvg",
    "sf",
    "tmap",
    "ggspatial",
    "prettymapr",
    "units"
)

# Try to install packages if not installed
default_options <- options()
tryCatch(
    {
        # Disable interactivity
        options(install.packages.compile.from.source = "always")
        
        # Install package if not installed
        for (package in required_packages) {
            is_package_installed <- require(package, character.only = TRUE)
            if (!is_package_installed) {
                cat(paste0("Installing package: ", package, "\n"))
                install.packages(package)
            } else {
                cat(paste0("Package already installed: ", package, "\n"))
            }
        }
    },
    error = function(cond) {
        stop(cond)
    },
    finally = {
        options(default_options) # reset interactivity
    }
)

Load R libraries.

library(DiagrammeR)
library(ggplot2)
library(ggspatial)
library(glue)
library(lubridate)
library(patchwork)
library(sf)
library(tidyverse)
library(tmap)

Data

Read data from the data folder.

ddesc <- read_csv("../data/data.csv")
ddesc

Vancouver Bikeways

Bikeways data with manually verified (Google Street View/Earth and Web Search) painted lanes and cycle tracks for Vancouver, Canada

# Read data
vancbike_raw <- read_sf("../data/vancouver-bikeways-2024-06-02.geojson")

# Get download date
vancbike_dldate <- ddesc %>% filter(
    file == "vancouver-bikeways-2024-06-02.geojson"
) %>% pull(download_date)

Map

Only the first 1000 records are shown.

tmap_mode("view")
tm_shape(vancbike_raw %>% head(1000)) +
    tm_lines(
        col = "#336699",
        border.col = "white",
        popup.vars = TRUE
    )

Data

  • Columns: 23
  • Rows: 3666
vancbike_raw %>% as_tibble

Dictionary

The data contains the following columns:

#vancbike_ddict <- read_csv("../data/vancouver-bikeways-2024-06-02-datadict.csv")
#vancbike_ddict

Details

print(vancbike_raw)
## Simple feature collection with 3666 features and 22 fields
## Geometry type: LINESTRING
## Dimension:     XY
## Bounding box:  xmin: -123.2238 ymin: 49.19899 xmax: -123.0233 ymax: 49.31428
## Geodetic CRS:  WGS 84
## # A tibble: 3,666 × 23
##    id     street     status road_type road_type_recode install_year install_type
##    <chr>  <chr>      <chr>  <chr>     <chr>                   <dbl> <chr>       
##  1 294725 Highbury   Active Resident… Local                    2006 Local Street
##  2 294726 Highbury   Active Resident… Local                    2006 Local Street
##  3 294731 W 8th Ave  Active Resident… Local                    1994 Local Street
##  4 294732 W 8th Ave  Active Resident… Local                    1994 Local Street
##  5 294733 Off Street Active Lane      Local                    2003 Protected B…
##  6 294736 W 5th Ave  Active Resident… Local                    2009 Local Street
##  7 294737 W 8th Ave  Active Resident… Local                    1994 Local Street
##  8 294738 W 7th Ave  Active Resident… Local                    1994 Local Street
##  9 294739 W 7th Ave  Active Resident… Local                    1994 Local Street
## 10 294742 W 7th Ave  Active Resident… Local                    1994 Local Street
## # ℹ 3,656 more rows
## # ℹ 16 more variables: verify_install_year <dbl>, verify_install_date <chr>,
## #   verify_install_type <chr>, verify_install_comment <chr>,
## #   verify_upgrade1_year <dbl>, verify_upgrade1_date <chr>,
## #   verify_upgrade1_type <chr>, verify_upgrade1_comment <chr>,
## #   verify_upgrade2_year <dbl>, verify_upgrade2_date <chr>,
## #   verify_upgrade2_type <chr>, verify_upgrade2_comment <chr>, …

Calgary Bikeways

Bikeways data with manually verified (Google Street View/Earth and Web Search) painted lanes and cycle tracks for Calgary, Canada

# Read data
calgbike_raw <- read_sf("../data/calgary-bikeways-2024-06-05.geojson")

# Get download date
calgbike_dldate <- ddesc %>% filter(
    file == "calgary-bikeways-2024-06-05.geojson"
) %>% pull(download_date)

Map

Only the first 1000 records are shown.

tmap_mode("view")
tm_shape(calgbike_raw %>% head(1000)) +
    tm_lines(
        col = "#336699",
        border.col = "white",
        popup.vars = TRUE
    )

Data

  • Columns: 22
  • Rows: 4169
calgbike_raw %>% as_tibble

Dictionary

The data contains the following columns:

#calgbike_ddict <- read_csv("../data/calgary-bikeways-2024-06-05-datadict.csv")
#calgbike_ddict

Details

print(calgbike_raw)
## Simple feature collection with 4169 features and 21 fields
## Geometry type: MULTILINESTRING
## Dimension:     XY
## Bounding box:  xmin: -114.269 ymin: 50.89762 xmax: -113.9302 ymax: 51.17778
## Geodetic CRS:  WGS 84
## # A tibble: 4,169 × 22
##    id    street status   road_type road_type_recode install_year install_type   
##    <chr> <chr>  <chr>    <chr>     <chr>                   <dbl> <chr>          
##  1 1     <NA>   EXISTING <NA>      <NA>                     2003 On-Street Bike…
##  2 2     <NA>   EXISTING <NA>      <NA>                     2009 On-Street Bike…
##  3 3     <NA>   EXISTING <NA>      <NA>                     2009 On-Street Bike…
##  4 4     <NA>   EXISTING <NA>      <NA>                     1999 On-Street Bike…
##  5 5     <NA>   EXISTING <NA>      <NA>                     1999 On-Street Bike…
##  6 6     <NA>   EXISTING <NA>      <NA>                     2005 On-Street Bike…
##  7 7     <NA>   EXISTING <NA>      <NA>                     1999 On-Street Bike…
##  8 8     <NA>   EXISTING <NA>      <NA>                     1999 On-Street Bike…
##  9 9     <NA>   EXISTING <NA>      <NA>                     1999 On-Street Bike…
## 10 10    <NA>   INACTIVE <NA>      <NA>                       NA DECOMMISSIONED 
## # ℹ 4,159 more rows
## # ℹ 15 more variables: verify_install_year <dbl>, verify_install_date <chr>,
## #   verify_install_type <chr>, verify_install_comment <chr>,
## #   verify_upgrade1_year <dbl>, verify_upgrade1_date <chr>,
## #   verify_upgrade1_type <chr>, verify_upgrade1_comment <chr>,
## #   verify_upgrade2_year <dbl>, verify_upgrade2_date <chr>,
## #   verify_upgrade2_type <chr>, verify_upgrade2_comment <chr>, …

Toronto Bikeways

Bikeways data with manually verified (Google Street View/Earth and Web Search) painted lanes and cycle tracks for Toronto, Canada

# Read data
toronbike_raw <- read_sf("../data/toronto-bikeways-2024-06-02.geojson")

# Get download date
toronbike_dldate <- ddesc %>% filter(
    file == "toronto-bikeways-2024-06-02.geojson"
) %>% pull(download_date)

Map

Only the first 1000 records are shown.

tmap_mode("view")
tm_shape(toronbike_raw %>% head(1000)) +
    tm_lines(
        col = "#336699",
        border.col = "white",
        popup.vars = TRUE
    )

Data

  • Columns: 23
  • Rows: 1323
toronbike_raw %>% as_tibble

Dictionary

The data contains the following columns:

#toronbike_ddict <- read_csv("../data/toronto-bikeways-2024-06-02-datadict.csv")
#toronbike_ddict

Details

print(toronbike_raw)
## Simple feature collection with 1323 features and 22 fields
## Geometry type: MULTILINESTRING
## Dimension:     XY
## Bounding box:  xmin: -79.63039 ymin: 43.58221 xmax: -79.11803 ymax: 43.85546
## Geodetic CRS:  WGS 84
## # A tibble: 1,323 × 23
##    id    street    street_from street_to road_type road_type_recode install_year
##    <chr> <chr>     <chr>       <chr>     <chr>     <chr>                   <dbl>
##  1 8     Bloor St… Parliament… Castle F… Major Ar… Arterial                 2001
##  2 17    Lake Sho… Humber Bay… Humber B… Major Ar… Arterial                 2001
##  3 18    Lake Sho… 37 M E Fle… Humber B… Major Ar… Arterial                 2001
##  4 19    Lake Sho… 50.7 M E L… 37 M E F… Major Ar… Arterial                 2001
##  5 38    Queens Q… Martin Goo… Bathurst… Collector Collector                2001
##  6 39    Davenpor… Cottingham… Macphers… Minor Ar… Arterial                 2001
##  7 40    Elizabet… College St  Gerrard … Collector Collector                2001
##  8 41    Gerrard … Yonge St    Church St Minor Ar… Arterial                 2001
##  9 42    Macphers… Davenport … Poplar P… Collector Collector                2001
## 10 43    Lake Sho… Marine Par… Palace P… Major Ar… Arterial                 2001
## # ℹ 1,313 more rows
## # ℹ 16 more variables: install_type <chr>, verify_install_year <dbl>,
## #   verify_install_date <chr>, verify_install_type <chr>,
## #   verify_install_comment <chr>, verify_upgrade1_year <dbl>,
## #   verify_upgrade1_date <chr>, verify_upgrade1_type <chr>,
## #   verify_upgrade1_comment <chr>, verify_upgrade2_year <dbl>,
## #   verify_upgrade2_date <chr>, verify_upgrade2_type <chr>, …

Verified Dates

  • Download Link:
  • Download Date:
  • Data Updated:
  • Notes:
# Read data
vdates_raw <- read_csv("../data/verify-dates-2024-06-07.csv")

# Get download date
vdates_dldate <- ddesc %>% filter(
    file == "verify-dates-2024-06-07.csv"
) %>% pull(download_date)

Data

  • Columns: 8
  • Rows: 298
vdates_raw

Dictionary

The data contains the following columns:

vdates_ddict <- read_csv("../data/verify-dates-2024-06-07-datadict.csv")
vdates_ddict

Files

The data files are available below:

Toronto KSI

KSI (2006-2022) data from the Toronto Police Service (TPS) Public Safety Data Portal for Toronto, Ontario

# Read data
ksi_raw <- read_sf("../data/toronto-ksi-2024-06-01.geojson")

# Get download date
ksi_dldate <- ddesc %>% filter(
    file == "toronto-ksi-2024-06-01.geojson"
) %>% pull(download_date)

Map

Note: Due to the large number of records, only the latest year of 2023 is displayed (n = 695).

tmap_mode("view")
tm_shape(ksi_raw %>% filter(year(DATE) == max(year(DATE)))) +
    tm_dots(
        col = "ACCLASS",
        clustering = TRUE,
        popup.vars = TRUE
    )

Data

  • Columns: 53
  • Rows: 18957
ksi_raw %>% as_tibble()

Dictionary

The data contains the following columns:

ksi_ddict <- read_csv("../data/toronto-ksi-2024-06-01-datadict.csv")
ksi_ddict

Details

print(ksi_raw)
## Simple feature collection with 18957 features and 52 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -79.63839 ymin: 43.58968 xmax: -79.12297 ymax: 43.85545
## Geodetic CRS:  WGS 84
## # A tibble: 18,957 × 53
##    OBJECTID INDEX_  ACCNUM DATE                TIME  STREET1      STREET2 OFFSET
##       <int> <chr>   <chr>  <dttm>              <chr> <chr>        <chr>   <chr> 
##  1        1 3389067 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  2        2 3389068 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  3        3 3389069 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  4        4 3389070 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  5        5 3389071 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  6        6 3389072 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  7        7 3389073 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  8        8 3389074 893184 2006-01-01 05:00:00 236   WOODBINE AVE O CONN… <NA>  
##  9        9 3433023 909646 2006-01-01 05:00:00 315   DANFORTH AVE WEST L… <NA>  
## 10       10 3433024 909646 2006-01-01 05:00:00 315   DANFORTH AVE WEST L… <NA>  
## # ℹ 18,947 more rows
## # ℹ 45 more variables: ROAD_CLASS <chr>, DISTRICT <chr>, LATITUDE <dbl>,
## #   LONGITUDE <dbl>, ACCLOC <chr>, TRAFFCTL <chr>, VISIBILITY <chr>,
## #   LIGHT <chr>, RDSFCOND <chr>, ACCLASS <chr>, IMPACTYPE <chr>, INVTYPE <chr>,
## #   INVAGE <chr>, INJURY <chr>, FATAL_NO <int>, INITDIR <chr>, VEHTYPE <chr>,
## #   MANOEUVER <chr>, DRIVACT <chr>, DRIVCOND <chr>, PEDTYPE <chr>,
## #   PEDACT <chr>, PEDCOND <chr>, CYCLISTYPE <chr>, CYCACT <chr>, …

Files

The data files are available below:

Cleaning

Combine Bikeways

Combine bikeway data across all cities.

# List of city bikeway data
bike_list <- list(
    vancouver = vancbike_raw,
    calgary = calgbike_raw %>%
        mutate(no_verify_install_type = NA),
    toronto = toronbike_raw %>%
        mutate(no_verify_install_type = NA)
)

# Get common columns across all city bikeways
bike_cols <- bike_list %>%
    map(colnames) %>%
    reduce(intersect)

# Combine bikeway data across cities
bike_raw <- names(bike_list) %>%
    map(function(city) {
        bike_list[[city]] %>%
            select(
                all_of(bike_cols)
            ) %>%
            mutate(
                city = factor(city, levels = names(bike_list)),
                .before = 1
            )
    }) %>%
    reduce(add_row)

Join Clean Dates

Join ambiguous verified install/upgrade dates (e.g. Jan 1/2022, 2022/02, Fall 2020) to manually cleaned dates with structured time units (e.g. days, months, quarters, semesters, ranges) and date formats (e.g. 2022-01-01, 2022-02-01).

Each of verify_install_date, verify_upgrade1_date and verify_upgrade2_date will have a set of cleaned structured date columns:

  • verify_date_raw,
  • verify_date_raw_count,
  • verify_date_type,
  • verify_date,
  • verify_date_start,
  • verify_date_end,
  • verify_date_prepost,
  • verify_date_notes
# Join clean dates to include structured date formats
for (event in c("install", "upgrade1", "upgrade2")) {
    
    # Date col names
    date_col <- glue("verify_{event}_date")
    clean_col <- glue("{event}_verify_date_raw")
    
    # Join clean dates
    bike_raw <- bike_raw %>%
        left_join( # join to installs
            vdates_raw %>%
                rename_with(
                    ~ paste0(event, "_", .x),
                    everything()
                ),
            by = set_names(clean_col, date_col)
        )
}

Add Columns

Add the following filter columns:

  • _is_verify: if a bikeway had a verified installation or upgrade
  • _is_verify_post2012: if a bikeway had a verified installation or upgrade after 2018
  • _is_verify_dated: if a bikeway had a verified installation or upgrade with dates
  • _is_verify_cdated: if a bikeway had a verified installation or upgrade with cleaned dates

Then add the following finest time unit columns for installs/upgrades:

  • install_verify_date_month: which month (1, 2, 3 … 12) a bikeway had verified installation
  • install_verify_date_quarter: which quarter (1, 2, 3, 4) of the year a bikeway had verified installation
  • install_verify_date_third: which third (1, 2, 3) of the year a bikeway had verified installation
  • install_verify_date_half: which half (1, 2) of the year a bikeway had verified installation
  • upgrade1_verify_date_month: which month (1, 2, 3 … 12) a bikeway had verified 1st upgrade
  • upgrade1_verify_date_quarter: which quarter (1, 2, 3, 4) of the year a bikeway had verified 1st upgrade
  • upgrade1_verify_date_third: which third (1, 2, 3) of the year a bikeway had verified 1st upgrade
  • upgrade1_verify_date_half: which half (1, 2) of the year a bikeway had verified 1st upgrade
  • upgrade2_verify_date_month: which month (1, 2, 3 … 12) a bikeway had verified 2nd upgrade
  • upgrade2_verify_date_quarter: which quarter (1, 2, 3, 4) of the year a bikeway had verified 2nd upgrade
  • upgrade2_verify_date_third: which third (1, 2, 3) of the year a bikeway had verified 2nd upgrade
  • upgrade2_verify_date_half: which half (1, 2) of the year a bikeway had verified 2nd upgrade
# Add filter columns
bike_raw <- bike_raw %>%
    mutate(
        `_is_verify` =
            (!is.na(verify_install_year) |
             !is.na(verify_upgrade1_year) |
             !is.na(verify_upgrade2_year)) &
            is.na(no_verify_install_type),
        `_is_verify_post2012` = 
            `_is_verify` &
            verify_install_year > 2012 |
            verify_upgrade1_year > 2012 |
            verify_upgrade2_year > 2012,
        `is_verify_dated` =
            `_is_verify` &
            !is.na(verify_install_date) |
            !is.na(verify_upgrade2_date) |
            !is.na(verify_upgrade2_date),
        `is_verify_cdated` =
            `_is_verify` &
            !is.na(install_verify_date_type) |
            !is.na(upgrade1_verify_date_type) |
            !is.na(upgrade2_verify_date_type)
    )

# Add time unit columns for month, quarter, third, half
for (event in c("install", "upgrade1", "upgrade2")) {
    
    # Date col name
    date_col <- glue("{event}_verify_date")
    start_col <- glue("{event}_verify_date_start")
    end_col <- glue("{event}_verify_date_end")
    type_col <- glue("{event}_verify_date_type")
    
    # Time unit col name
    month_col <- glue("{event}_verify_date_month")
    quarter_col <- glue("{event}_verify_date_quarter")
    third_col <- glue("{event}_verify_date_third")
    half_col <- glue("{event}_verify_date_half")
    
    # Add time unit columns via mutate
    bike_raw <- bike_raw %>%
        mutate(
            
            # Months (monthly)
            !!month_col := case_when(
                .data[[type_col]] %in% c("day", "month") ~ month(.data[[date_col]], label = T, abbr = F)
            ),
            !!month_col := as.numeric(.data[[month_col]]),
            
            # Quarters (quarterly)
            !!quarter_col := case_when(
                month(.data[[date_col]]) %in% 1:3 |
                (
                    month(.data[[start_col]]) %in% 1:3 &
                    month(.data[[end_col]]) %in% 1:3 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 1,
                month(.data[[date_col]]) %in% 4:6 |
                (
                    month(.data[[start_col]]) %in% 4:6 &
                    month(.data[[end_col]]) %in% 4:6 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 2,
                month(.data[[date_col]]) %in% 1:3 |
                (
                    month(.data[[start_col]]) %in% 7:9 &
                    month(.data[[end_col]]) %in% 7:9 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 3,
                month(.data[[date_col]]) %in% 10:12 |
                (
                    month(.data[[start_col]]) %in% 10:12 &
                    month(.data[[end_col]]) %in% 10:12 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 4
            ),
            
            # Thirds (triyearly)
            !!third_col := case_when(
                month(.data[[date_col]]) %in% 1:4 |
                (
                    month(.data[[start_col]]) %in% 1:4 &
                    month(.data[[end_col]]) %in% 1:4 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 1, # Fall
                month(.data[[date_col]]) %in% 5:8 |
                (
                    month(.data[[start_col]]) %in% 5:8 &
                    month(.data[[end_col]]) %in% 5:8 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 2, # Winter
                month(.data[[date_col]]) %in% 9:12 |
                (
                    month(.data[[start_col]]) %in% 9:12 &
                    month(.data[[end_col]]) %in% 9:12 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 3 # Spring/Summer
            ),
            
            # Halves (biyearly)
            !!half_col := case_when(
                month(.data[[date_col]]) %in% 1:6 |
                (
                    month(.data[[start_col]]) %in% 1:6 &
                    month(.data[[end_col]]) %in% 1:6 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 1,
                month(.data[[date_col]]) %in% 7:12 |
                (
                    month(.data[[start_col]]) %in% 7:12 &
                    month(.data[[end_col]]) %in% 7:12 &
                    year(.data[[start_col]]) == year(.data[[end_col]])
                ) ~ 2
            )
            
        )
}

Determine Unit of Time

Determine the temporal resolution (unit of time) finer than yearly based on the amount of data available per time unit (sorted from the highest resolution time unit to the lowest resolution time unit):

  • Month: refers to verified post-2012 installs and upgrades occurring approximately in a month (1/12) of a year
  • Quarter: refers to verified post-2012 installs and upgrades occurring approximately in a quarter (1/4) of a year
  • Third: refers to verified post-2012 installs and upgrades occurring approximately in a third (1/3) of a year
  • Half: refers to verified post-2012 installs and upgrades occurring approximately in a half (1/2) of a year

As there seems to be a large improvement in the percentage of records across cities from quarters to thirds of a year, and diminishing improvements when lowering the resolution to halves of a year, thirds of a year was chosen as the unit of time.

# Prepare plot data
unit_data <- bike_raw %>%
    as_tibble %>%
    filter(`_is_verify_post2012`) %>%
    select(
        city,
        install_verify_date_month,
        install_verify_date_quarter,
        install_verify_date_third,
        install_verify_date_half,
        upgrade1_verify_date_month,
        upgrade1_verify_date_quarter,
        upgrade1_verify_date_third,
        upgrade1_verify_date_half,
        upgrade2_verify_date_month,
        upgrade2_verify_date_quarter,
        upgrade2_verify_date_third,
        upgrade2_verify_date_half
    ) %>%
    pivot_longer(
        cols = -city,
        names_to = "column",
        values_to = "value"
    ) %>%
    mutate(
        type = case_when(
            str_detect(column, "month") & !is.na(value) ~ "Month",
            str_detect(column, "quarter") & !is.na(value) ~ "Quarter",
            str_detect(column, "third") & !is.na(value) ~ "Third",
            str_detect(column, "half") & !is.na(value) ~ "Half"
        )
    ) %>%
    group_by(city, type) %>%
    count %>%
    filter(!is.na(type)) %>%
    ungroup %>%
    left_join( # left join totals for perc
        bike_raw %>%
            as_tibble %>%
            filter(`_is_verify_post2012`) %>%
            select(
                city,
                verify_install_year,
                verify_upgrade1_year,
                verify_upgrade2_year
            ) %>%
            pivot_longer(
                cols = -city,
                names_to = "column",
                values_to = "value"
            ) %>%
            filter(!is.na(value)) %>%
            group_by(city) %>%
            count %>%
            ungroup %>%
            rename(total = n),
        by = "city"
    ) %>%
    mutate(
        perc = n / total * 100,
        perc_label = glue("{round(perc, 2)}%\n(n={n})"),
        type = factor(type, levels = c("Month", "Quarter", "Third", "Half")),
        city = factor(str_to_title(city), levels = c("Vancouver", "Calgary", "Toronto")),
    ) %>%
    group_by(type) %>%
    arrange(desc(perc)) %>% # adjust overlapping labels
    mutate(
        perc_label_y = case_when(
            lag(perc) - perc < 1 ~ perc - 1.95,
            lead(perc) - perc > -1 ~ perc + 1.95,
            .default = perc
        )
    ) %>%
    ungroup %>%
    group_by(city) %>%
    mutate( # add city labels at end of lines
        city_label = if_else(type == "Half", glue("{city}\n(n={total})"), NA)
    ) %>%
    ungroup %>%
    arrange(city, type)

# Plot line
unit_plot <- unit_data %>%
    ggplot(aes(
        x = type,
        y = perc,
        group = city,
        color = city,
        label = perc_label
    )) +
    geom_line(
        alpha = 0.8,
        linewidth = 1.5
    ) +
    geom_label(
        aes(y = perc_label_y),
        size = 2.5,
        show.legend = F,
        label.padding = unit(0.5, "lines")
    ) +
    geom_text(
        aes(
            label = city_label,
            y = perc_label_y
        ),
        size = 3,
        show.legend = F,
        hjust = 0,
        nudge_x = 0.2
    ) +
    scale_y_continuous(labels = function(x) paste0(x, "%")) +
    scale_x_discrete(
        limits = levels(unit_data$type),
        position = "top"
    ) +
    labs(
        title = glue(
            "% of Verified Post-2012 Installs & Upgrades by Unit of Time\n",
            "(n={sum(unit_data$total %>% unique, na.rm = T)})"
        ),
        x = NULL,
        y = NULL,
        color = "City",
        label = NULL,
        group = NULL
    ) +
    theme_minimal() +
    theme(
        legend.position = "none",
        plot.title = element_text(hjust = 0.5)
    )
unit_plot

# Select time unit
time_unit = "third"

Join KSI